<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Request;

class ApiController extends Controller
{
    protected $account;

    /**
     * 不鉴权router
     */
    protected $excludeRouter = [
        'api/token',
        'api/upload',
        'api/banners',
        'api/advertisings',
        'api/contents',
        'api/contents/{content}',
        'api/positions',
        'api/mobile',
        'api/test'
    ];

    // 方法前置检查器
    function callAction($method, $parameters)
    {
        $token = Request::header('token');
        $userId = !empty($token) ? cache($token) : null;
        logger('request logger', [
            'userId' => $userId,
            'token' => $token,
            'path' => Request::fullUrl(),
            'params' => Request::input(),
        ]);

        // $token = 'aaaaa';
        // $userId = 1;

        if (!in_array(Route::current()->uri(), $this->excludeRouter, true)) {
            if (empty($token) || !$userId) {
                return $this->errorReturn('Access denied.');
            }
        }
        App::singleton('userId', function() use ($userId) {
            return $userId;
        });
        return parent::callAction($method, $parameters);
    }

    /* 成功返回 */
    protected function okReturn($result = true)
    {
        return [
            'code' => 200,
            'message' => 'SUCCESS',
            'data' => $result,
        ];
    }

    /* 错误返回 */
    protected function errorReturn($message = null, $code = -1)
    {
        return [
            'code' => $code,
            'message' => $message ?? 'Unknown error.',
        ];
    }

    /* 无权访问 */
    protected function accessDenied($message = null)
    {
        return [
            'code' => 403,
            'message' => $message ?? 'Access denied.',
        ];
    }
}
